<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Http\Controllers\RedisServiceController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 用户使用抽奖机会表
 */
class TurnActivityUserUsePrizeRecord extends BaseModel
{
    use HasFactory;

    public $start_time = null; //抽奖开始时间
    public $end_time = null; //抽奖结束时间

    public $gift_grant_start_time = null; //礼品发放开始时间
    public $gift_grant_end_time = null; //礼品发放结束时间

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'turn_activity_user_use_prize_record';

    /**
     * 判断是否有人抽奖
     * @param act_id 活动id
     */
    public function isDraw($act_id)
    {
        return $this->where('act_id', $act_id)->first();
    }

    /**
     * 获取抽奖订单号
     */
    public function getDrawOrderId($number, $order_key)
    {
        $redisObj = RedisServiceController::getInstance();

        while ($number >= 0) {
            try {
                $order_id = get_order_id();

                $is_exists = $this->where('order_id', $order_id)->first();
                if ($is_exists) {
                    throw new \Exception("The order number already exists");
                }

                //判断订单号是否存在
                $is_exists = $redisObj->valueExists($order_key . $order_id);

                if ($is_exists) {
                    throw new \Exception("The order number already exists");
                }

                return $order_id;
            } catch (\Exception $e) {
                --$number;
            }
        }
        return false;
    }


    /**
     * 判断用户今日是否有抽奖机会 返回抽奖次数
     * @param $act_id 活动id
     * @param $user_guid 用户guid
     * @param $act_info 活动详情
     */
    public function getSurplusPrizeNumber($act_id, $user_guid, $act_info)
    {
        switch ($act_info['node']) {
            case 1:
                $res = $this->onceDraw($act_info['vote_way'], $act_info['turn_start_time'], $act_info['turn_end_time']);
                break;
            case 2:
                $res = $this->weekDraw($act_info['vote_way'], $act_info['execute_day'], $act_info['turn_start_time'], $act_info['turn_end_time']);
                break;
            case 3:
                $res = $this->monthDraw($act_info['vote_way'], $act_info['execute_day'], $act_info['turn_start_time'], $act_info['turn_end_time']);
                break;
        }
        if (!$res) {
            return -1; //今日不可抽奖
        }
        list($start_time, $end_time , $gift_grant_start_time , $gift_grant_end_time) = $res;

        $this->start_time = $start_time;
        $this->end_time = $end_time;
        $this->gift_grant_start_time = $gift_grant_start_time;
        $this->gift_grant_end_time = $gift_grant_end_time;

        //已抽奖次数
        $already_number = $this->getDrawNumber($act_id, $user_guid, $start_time, $end_time);

        //获取分享次数
        $turnActivityUserGiftModel = new TurnActivityShare();
        $share_number = $turnActivityUserGiftModel->getUserShareNumber($act_id, $user_guid, null, $start_time, $end_time);
        $share_number = $share_number < $act_info['share_number'] ? $share_number :  $act_info['share_number'];
        $number =  $act_info['number'] + $share_number; //总次数
        $surplus_number = $number - $already_number;

        return $surplus_number; //返回抽奖次数
    }
    /**
     * 判断单次抽奖机会
     * @param vote_way 活动执行方式    1 总数量形式   2 每日执行形式
     * @param turn_start_time
     * @param turn_end_time
     */
    public function onceDraw($vote_way, $turn_start_time, $turn_end_time)
    {
        if ($vote_way == 1) {
            $start_time = $turn_start_time;
            $end_time = $turn_end_time;
        } else {
            $start_time = date('Y-m-d', strtotime($turn_start_time)) == date('Y-m-d') ? $turn_start_time : date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d', strtotime($turn_end_time)) == date('Y-m-d') ? $turn_end_time : date('Y-m-d 23:59:59');
        }


        $gift_grant_start_time = null;//单次不限制时间
        $gift_grant_end_time = null;
        return [$start_time, $end_time,$gift_grant_start_time,$gift_grant_end_time];
    }
    /**
     * 判断周抽奖机会
     * @param vote_way 活动执行方式    1 总数量形式   2 每日执行形式
     * @param execute_day
     */
    public function weekDraw($vote_way, $execute_day, $turn_start_time, $turn_end_time)
    {
        $execute_day = explode(',', $execute_day);
        $week = date('w'); //从"0(星期天)"至"6(星期六)"
        $week = $week === '0' || $week === 0 ? 7 : $week;
        if (!in_array($week, $execute_day)) {
            return false; //无抽奖机会
        }
        list($start_time, $end_time) = get_week_time();

        $gift_grant_start_time = $start_time;//每周开始时间就以每周开始为准
        $gift_grant_end_time = $end_time;

        if ($vote_way == 1) {
            //获取当前周的开始时间和结束时间
            $start_time = $turn_start_time < $start_time ? $start_time : $turn_start_time;
            $end_time = $turn_end_time < $end_time ? $turn_end_time : $end_time;
        } else {
            $start_time = date('Y-m-d', strtotime($turn_start_time)) == date('Y-m-d') ? $turn_start_time : date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d', strtotime($turn_end_time)) == date('Y-m-d') ? $turn_end_time : date('Y-m-d 23:59:59');
        }

        return [$start_time, $end_time,$gift_grant_start_time,$gift_grant_end_time];
    }

    /**
     * 判断月抽奖机会
     * @param vote_way 活动执行方式    1 总数量形式   2 每日执行形式
     * @param execute_day
     */
    public function monthDraw($vote_way, $execute_day, $turn_start_time, $turn_end_time)
    {

        $execute_day = explode(',', $execute_day);
        $day = date('d'); //从"0(星期天)"至"6(星期六)"
        $day = $day === '0' || $day === 0 ? 7 : $day;
        if (!in_array($day, $execute_day)) {
            return false; //无抽奖机会
        }


        list($start_time, $end_time) = get_month_time();

        $gift_grant_start_time = $start_time;//每月开始时间就以每月开始为准
        $gift_grant_end_time = $end_time;

        if ($vote_way == 1) {
            //获取当前周的开始时间和结束时间
            $start_time = $turn_start_time < $start_time ? $start_time : $turn_start_time;
            $end_time = $turn_end_time < $end_time ? $turn_end_time : $end_time;
        } else {
            $start_time = date('Y-m-d', strtotime($turn_start_time)) == date('Y-m-d') ? $turn_start_time : date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d', strtotime($turn_end_time)) == date('Y-m-d') ? $turn_end_time : date('Y-m-d 23:59:59');
        }
        return [$start_time, $end_time,$gift_grant_start_time,$gift_grant_end_time];
    }

    /**
     * 获取用户抽奖次数
     * @param act_id 活动id
     * @param user_guid 用户guid
     * @param start_time 开始时间
     * @param end_time 结束时间
     */
    public function getDrawNumber($act_id, $user_guid, $start_time, $end_time)
    {
        $number = $this->where(function ($query) use ($user_guid, $start_time, $end_time) {
            if ($user_guid) {
                $query->where('user_guid', $user_guid);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->where('act_id', $act_id)
            ->count();
        return $number;
    }


    /**
     * 用户参与人次、答题次数统计
     * @param act_id 活动id
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     * @param type 类型 1 参与人次  2 抽奖次数
     */
    public function partNumberStatistics($act_id, $start_time = null, $end_time = null, $type = 1)
    {
        $res = $this->select('id', 'user_guid', 'act_id')->where(function ($query) use ($act_id, $start_time, $end_time) {
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        });

        if ($type == 1) {
            $res = $res->groupBy('user_guid');
        }
        $result = $res->get()->toArray();

        return count($result);
    }

    /**
     * 答题次数统计(折线图)
     * @param act_id 活动id
     * @param unit_id 单位id 数组形式
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     *  @param is_month  是否按月统计
     */
    public function partStatistics($act_id, $start_time = null, $end_time = null, $is_month = false)
    {
        if (empty($start_time)) {
            $start_time = date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d H:i:s');
        }
        if ($is_month) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m') as times"), DB::raw("count(id) as count")];
        } elseif (date('Y-m-d' , strtotime($start_time)) == date('Y-m-d' , strtotime($end_time))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as times"), DB::raw("count(id) as count")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as times"), DB::raw("count(id) as count")];
        }
        $res = $this->select($field)->where(function ($query) use ($act_id, $start_time, $end_time) {
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->orderBy('times')
            ->groupBy('times')
            ->get()
            ->toArray();

        return $res;
    }
}
